<template>
  <div>
    <!-- 面包屑的区域   -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="queryInfo.query"
            placeholder="请输入用户名搜索"
            :clearable="true"
            @clear="getUserList"
          >
            <el-button slot="append" icon="el-icon-search" @click="search">
            </el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addNewUser">添加用户 </el-button>
        </el-col>
      </el-row>

      <!-- table列表渲染数据区域  -->
      <el-table :data="userList" style="width: 100%">
        <el-table-column label="序号" type="index" width="80"></el-table-column>
        <el-table-column
          label="用户名"
          prop="UserName"
          width="100"
        ></el-table-column>
        <el-table-column
          label="手机"
          prop="Mobile"
          width="180"
        ></el-table-column>
        <el-table-column
          label="邮箱"
          prop="Email"
          width="180"
        ></el-table-column>
        <el-table-column
          label="角色"
          prop="RoleName"
          width="100"
        ></el-table-column>
        <el-table-column label="状态" prop="MgState" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.MgState"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userstateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              @click="updateUserDialog(scope.row)"
              type="success"
              size="mini"
              >修改</el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="deleteuser(scope.row.id)"
              >删除</el-button
            >
            <div></div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 以下是分页功能  -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 7, 9]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 对话框 dialog1 -->
    <!-- <el-dialog @update:visible="bol=>dialogVisible=bol"  :visible='dialogVisible'/>   -->
    <el-dialog
      title="添加用户信息"
      :visible.sync="dialogVisible"
      width="40%"
      @close="handleClosedAddUser"
    >
      <el-form
        ref="addUserForm"
        :rules="addFormRules"
        :model="addForm"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="enterAddUser">确定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户弹出框 -->

    <!--修改用户信息对话框-->
    <el-dialog
      title="修改用户信息"
      :visible.sync="updateUserDialogVisible"
      width="40%"
      @close="updateDialogClosed"
    >
      <el-form
        ref="updateFormRef"
        :rules="addFormRules"
        :model="updateForm"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="updateForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="updateForm.password" disabled></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updateForm.email"></el-input>
        </el-form-item>

        <el-form-item label="电话" prop="mobile">
          <el-input v-model="updateForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUserenter">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "login",
  props: [],
  components: {},
  data() {
    return {
      queryInfo: { query: "", pagenum: 1, pagesize: 3, id: "" },
      userList: [],
      total: 10,
      dialogVisible: false,
      // 修改用户，布尔值
      updateUserDialogVisible: false,
      // 添加用户表单双向数据绑定
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
        pagenum: "",
        pagesize: "",
      },
      // 修改用户表单双向数据绑定
      updateForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
        pagenum: "",
        pagesize: "",
      },
      // 校验规则
      addFormRules: {
        username: [
          //required 必填
          //message 信息提示
          //trigger 鼠标失去焦点时触发
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          // { validator: checkEmail, trigger: 'blur' },
          {
            pattern: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
            message: "输入正确邮箱规则22",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          // { validator: checkMobile, trigger: 'blur' }
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "请输入正确手机号",
            trigger: "blur",
          },
        ],
      },
    };
  },
  //方法 函数写这里
  methods: {
    async getUserList() {
      const res = await this.$http.get("/api/users", {
        params: this.queryInfo,
      });

      console.log("res 用户列表数据 ", res);
      this.userList = res.data.data;
      this.total = res.data.total;
    },
    // 子组件点击分页的 1 2 3 4页码会发送一个 this.$emit('current-change',index)
    handleCurrentChange(newpage) {
      console.log(" handleCurrentChange");

      this.queryInfo.pagenum = newpage;
      this.getUserList();
    },
    // 子组件选择 一页几条的时候触发一个this.$emit('size-change',index)
    handleSizeChange(newsize) {
      console.log(newsize);
      this.queryInfo.pagesize = newsize;
      this.getUserList();
    },
    //  switch 改变 用户状态时间
    async userstateChanged(userinfo) {
      console.log("userinfo", userinfo);
      const res = await this.$http.get("/api/userupdate", { params: userinfo });
      if (res.data.code != 200) {
        alert("改变数据请求失败");
        return;
      }

      this.$message.success("此用户状态已经改变" + res.data.newState);
    },

    async search() {
      const res = await this.$http.get("/api/usersearch", {
        params: this.queryInfo,
      });
      console.log("res 搜索结果", res);
      this.userList = res.data.data;
    },
    // 添加用户方法
    addNewUser() {
      this.dialogVisible = true;
    },
    // 关闭 添加用户表单的时候要清空里面的数据
    handleClosedAddUser() {
      this.$refs.addUserForm.resetFields();
    },

    // 关闭 修改用户表单的时候要清空里面的数据
    updateDialogClosed() {
      this.$refs.updateFormRef.resetFields();
    },
    // 添加用户的函数
    enterAddUser() {
      this.addForm.pagenum = this.queryInfo.pagenum;
      this.addForm.pagesize = this.queryInfo.pagesize;

      this.$refs.addUserForm.validate(async (valid) => {
        if (valid) {
          const res = await this.$http.get("/api/adduser", {
            params: this.addForm,
          });

          console.log("res 添加后的最新数据 ", res);
          this.userList = res.data.data;
          this.total = res.data.total;

          this.dialogVisible = false;
        } else {
          this.$message.error("输入不正确");
          return;
        }
      });
    },
    async deleteuser(id) {
      console.log("id", id);
      this.queryInfo.id = id;

      var res = await this.$confirm("此操作会删除用户确定了吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).catch((err) => {
        console.log("用户取消了");
        return;
      });
      console.log("res 最终选择", res);
      if (res != "confirm") return this.$message.info("删除用户已经取消");

      const resdata = await this.$http("/api/deleteuser", {
        params: this.queryInfo,
      });
      this.getUserList();
    },

    updateUserDialog(userInfo) {
      this.updateUserDialogVisible = true;
      console.log("row 修改用户的数据", userInfo);
      this.updateForm.id = userInfo.id;
      this.updateForm.username = userInfo.UserName;
      this.updateForm.password = userInfo.Password;
      this.updateForm.email = userInfo.Email;
      this.updateForm.mobile = userInfo.Mobile;
    },

    // 修改用户确定按钮
    updateUserenter() {
      // alert("updateuser");
      console.log("最后修改用户的调用数据库阶段");
      this.updateForm.pagenum = this.queryInfo.pagenum;
      this.updateForm.pagesize = this.queryInfo.pagesize


      this.$refs.updateFormRef.validate(async (valid)=>{
        if(valid){
          const res = await this.$http.get('/api/updateuser',{
            params:this.updateForm
          })

          this.userList = res.data.data;
          this.total = res.data.data;
          this.updateUserDialogVisible = false;
        }else{
          this.$message.info('数据格式不正确')
          return
        }
      })
    },
  },
  //计算属性
  computed: {},
  //侦听器
  watch: {},
  //过滤器
  filters: {},
  //以下是生命周期
  //组件创建之前
  beforeCreate() {},
  //组件创建之后
  created() {
    this.getUserList();
  },
  //页面渲染之前
  beforeMount() {},
  //页面渲染之后
  mounted() {
    console.log("mounted user");
  },
  //页面视图数据更新之前
  beforeUpdate() {},
  //页面视图数据更新之后
  updated() {},
  //页面销毁之前
  beforeDestroy() {},
  //页面销毁之后
  destroyed() {},
};
</script>


<style lang="scss"  scoped>
.el-card {
  margin-top: 15px;
  // height: 100px;
  box-shadow: 0 1px 1px #353333;
}

.el-breadcrumb {
  font-size: 12px;
}
</style>